package com.supertange.miniapp.wepet.modules.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.supertange.miniapp.wepet.common.controller.BaseController;
import com.supertange.miniapp.wepet.common.vo.AjaxResult;
import com.supertange.miniapp.wepet.modules.wepet.entity.UsersEntity;
import com.supertange.miniapp.wepet.modules.wepet.entity.vo.UsersVO;
import com.supertange.miniapp.wepet.modules.wepet.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 微信小程序用户接口
 */
@RestController
@RequestMapping("/wechat/user")
@Log4j2
public class WxMaUserController  extends BaseController {

    @Autowired
    private WxMaService wxService;
    @Autowired
    private UserService userService;

    /**
     * 登陆接口
     */
    @PostMapping("/login")
    public AjaxResult wxLogin(String code, String signature, String rawData, String encryptedData, String iv) {
        System.err.println(code);
        System.out.println("收到数据了:"+code);
        if (StringUtils.isBlank(code)) {
            return AjaxResult.errorMsg("code不能为空");
        }


        try {
            WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
            String sessionKey=session.getSessionKey();
            String openId=session.getOpenid();

            // 用户信息校验
            if (!this.wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
                return AjaxResult.errorMsg("获取信息失败");
            }
            // 解密用户信息
            WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

            // 解密
//            WxMaPhoneNumberInfo phoneNoInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

            UsersEntity user=userService.queryOpenidIsExist(userInfo.getOpenId());
            if(user!=null){
                UsersVO usersVO=setUserRedisSessionToken(user);
                return AjaxResult.ok(usersVO);
            }

            //保存用户信息
            UsersEntity usersEntity =new UsersEntity();
            usersEntity.setUsername(userInfo.getNickName());
            usersEntity.setNickname(userInfo.getNickName());
            usersEntity.setFaceImage(userInfo.getAvatarUrl());
            if (userInfo.getCity()!=null) usersEntity.setCity(userInfo.getCity()+"市");
            usersEntity.setCountry(userInfo.getCountry());
            usersEntity.setProvince(userInfo.getProvince());
            usersEntity.setGender(Integer.valueOf(userInfo.getGender()));
            usersEntity.setLanguage(userInfo.getLanguage());
            usersEntity.setUnionId(userInfo.getUnionId());
//            usersEntity.setPhone(phoneNoInfo.getPhoneNumber());
            usersEntity.setOpenid(openId);
            userService.saveUser(usersEntity);
            UsersVO usersVO=setUserRedisSessionToken(usersEntity);
            BeanUtils.copyProperties(usersEntity,usersVO);
            return AjaxResult.ok(usersVO);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.errorMsg("认证失败");
        }
    }

    @GetMapping("/loginfzk")
    public AjaxResult wxLogin2(String code,String encryptedData, String iv) {
        System.out.println("收到了数据:"+code);
        try {
            WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
            String sessionKey=session.getSessionKey();
            String openId=session.getOpenid();
            WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
            UsersEntity user=userService.queryOpenidIsExist(userInfo.getOpenId());
            if(user!=null){
//                UsersVO usersVO=setUserRedisSessionToken(user);
                return AjaxResult.ok(user);
            }
            //保存用户信息
            UsersEntity usersEntity =new UsersEntity();
            usersEntity.setUsername(userInfo.getNickName());
            usersEntity.setNickname(userInfo.getNickName());
            usersEntity.setFaceImage(userInfo.getAvatarUrl());
            if (userInfo.getCity()!=null) usersEntity.setCity(userInfo.getCity()+"市");
            usersEntity.setCountry(userInfo.getCountry());
            usersEntity.setProvince(userInfo.getProvince());
            usersEntity.setGender(Integer.valueOf(userInfo.getGender()));
            usersEntity.setLanguage(userInfo.getLanguage());
            usersEntity.setUnionId(userInfo.getUnionId());
//            usersEntity.setPhone(phoneNoInfo.getPhoneNumber());
            usersEntity.setOpenid(openId);
            userService.saveUser(usersEntity);
//            UsersVO usersVO=setUserRedisSessionToken(usersEntity);
//            BeanUtils.copyProperties(usersEntity,usersVO);
            return AjaxResult.ok(usersEntity);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return AjaxResult.errorMsg("认证失败");
        }
    }

}
